package no.ntnu.item.ttm4115.termproject.playeragent.gui;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

import org.jdesktop.swingx.JXMapKit;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.jdesktop.swingx.mapviewer.Waypoint;
import org.jdesktop.swingx.mapviewer.WaypointPainter;
import org.jdesktop.swingx.mapviewer.WaypointRenderer;
import org.jdesktop.swingx.painter.Painter;

import no.ntnu.item.ttm4115.termproject.CoordsFromGUI;
import no.ntnu.item.ttm4115.termproject.ForwardCoordsToGA;
import no.ntnu.item.ttm4115.termproject.ManuallyPosition;
import no.ntnu.item.ttm4115.termproject.extrasagent.Player;
import no.tellu.common.actorframe.ActorSM;
import no.tellu.common.javaframe.ActorAddress;


public class PlayerGameGUI  extends JPanel{
	
	//start of variable declarations
	private MeetingPlaceGUI mainFrame;
	private JPanel jPanelGameStart;
	private JTabbedPane jTabbedPaneGame;
	private JLabel jLabel6;
	private JLabel jLabel7;
	private JLabel jLabel11;
	private JLabel jLabel12;
	private JLabel jLabelClueInput;
	private JLabel jLabelGameNameInput;
	private JPanel jPanelMap;
	private JPanel jPanelClue;
	private JPanel jPanelLocMap;
	private JPanel jPanelClueLayout;
	private JTextField jTextFieldX;
	private JTextField jTextFieldY;
	private JButton jButtonSendCoor;
	private ActorSM asm;
	private String gameName;
	private JXMapKit jXMapKit1;
	private JButton jButtonViewClue;
	private JButton jButtonMyPosition;
	private javax.swing.JButton jButtonManUpdate;
	private javax.swing.JButton jButtonAutoUpdate;
	private ActorAddress positionAgent;
	private HashMap playerPositions;
	private String groupLeader;
	
	
	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	// End of variables declaration

     
	public PlayerGameGUI (ActorSM asm, MeetingPlaceGUI mainFrame,String gameName, ActorAddress positionAgent, String groupLeader){	

	this.groupLeader = groupLeader;
	this.positionAgent = positionAgent;
	this.mainFrame = mainFrame;
	this.mainFrame.getPane().addTab(gameName, this);
	this.repaint();
    this.mainFrame.repaint();
    this.asm = asm;
    this.gameName = gameName;
    playerPositions = new HashMap();
    jXMapKit1 = new org.jdesktop.swingx.JXMapKit();
	jLabel6 = new JLabel();
	jLabel7 = new JLabel();
	jLabel11 = new JLabel();
	jLabel12 = new JLabel();
	jLabelClueInput = new JLabel();
	jLabelGameNameInput = new JLabel();
	jPanelMap = new JPanel();
	jPanelClue = new JPanel();
	jPanelLocMap = new JPanel();
	jPanelClueLayout = new JPanel();
	jTextFieldX = new JTextField();
	jTextFieldY = new JTextField();
	jButtonSendCoor = new JButton();
	jButtonViewClue = new JButton();
	jButtonMyPosition = new JButton();
	jButtonManUpdate = new JButton();
	jButtonAutoUpdate = new JButton();
	
	
	initComponents();
	
	}
	
	public void initComponents(){

	jPanelGameStart = new javax.swing.JPanel();
	jTabbedPaneGame = new javax.swing.JTabbedPane();



        jPanelClue.setBorder(javax.swing.BorderFactory.createTitledBorder("Clue"));

        jLabelClueInput.setText("N/A");

        jTextFieldX.setText("X-Coordinate");

        jTextFieldY.setText("Y-Coordinate");

        jButtonSendCoor.setText("Send");

        javax.swing.GroupLayout jPanelClueLayout = new javax.swing.GroupLayout(jPanelClue);
        jPanelClue.setLayout(jPanelClueLayout);
        jPanelClueLayout.setHorizontalGroup(
            jPanelClueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelClueLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelClueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelClueLayout.createSequentialGroup()
                        .addComponent(jTextFieldX, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextFieldY, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonSendCoor, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabelClueInput, javax.swing.GroupLayout.PREFERRED_SIZE, 495, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        jPanelClueLayout.setVerticalGroup(
            jPanelClueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelClueLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabelClueInput)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelClueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonSendCoor))
                .addGap(23, 23, 23))
        );

        jPanelLocMap.setBorder(javax.swing.BorderFactory.createTitledBorder("Map"));

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("trondheim.gif"))); // NOI18N

        jLabel7.setText("To the left you can see");

        jLabel11.setText("your own location on the");

        jLabel12.setText("map.");

        //surya
        //jXMapKit1.setDefaultProvider(org.jdesktop.swingx.JXMapKit.DefaultProviders.Custom);
        jXMapKit1.setDefaultProvider(org.jdesktop.swingx.JXMapKit.DefaultProviders.OpenStreetMaps);
        
        jXMapKit1.getMainMap().setOverlayPainter(textOverlay);
        //surya
        //jXMapKit1.setTileFactory(GoogleMapsTileProvider.getDefaultTileFactory());
        jXMapKit1.setAddressLocation(new GeoPosition(63.43086,10.437012));
        jXMapKit1.setZoom(5);
        jXMapKit1.setMiniMapVisible(true);
        
        jButtonViewClue.setText("View Clue");
        jButtonViewClue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonViewClueActionPerformed(evt);
            }
        });

        jButtonMyPosition.setText("My Position");
        jButtonMyPosition.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonMyPositionActionPerformed(evt);
            }
        });
        
        jButtonManUpdate.setText("Manually Update");
        jButtonManUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonManUpdateActionPerformed(evt);
            }
        });

        jButtonAutoUpdate.setText("Auto Update");
        jButtonAutoUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAutoUpdateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelLocMapLayout = new javax.swing.GroupLayout(jPanelLocMap);
        jPanelLocMap.setLayout(jPanelLocMapLayout);
        jPanelLocMapLayout.setHorizontalGroup(
            jPanelLocMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelLocMapLayout.createSequentialGroup()
                .addComponent(jButtonViewClue)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonMyPosition)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonManUpdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonAutoUpdate)
                .addContainerGap(141, Short.MAX_VALUE))
            .addComponent(jXMapKit1, javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
        );
        jPanelLocMapLayout.setVerticalGroup(
            jPanelLocMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelLocMapLayout.createSequentialGroup()
                .addComponent(jXMapKit1, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelLocMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonViewClue)
                    .addComponent(jButtonMyPosition)
                    .addComponent(jButtonManUpdate)
                    .addComponent(jButtonAutoUpdate))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        
        jLabelGameNameInput.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabelGameNameInput.setText("TreasureHunt");

        javax.swing.GroupLayout jPanelMapLayout = new javax.swing.GroupLayout(jPanelMap);
        jPanelMap.setLayout(jPanelMapLayout);
        jPanelMapLayout.setHorizontalGroup(
            jPanelMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelMapLayout.createSequentialGroup()
                .addGroup(jPanelMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanelClue, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelMapLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabelGameNameInput))
                    .addComponent(jPanelLocMap, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanelMapLayout.setVerticalGroup(
            jPanelMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelMapLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelGameNameInput)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelLocMap, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelClue, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
	jTabbedPaneGame.addTab("Map", jPanelMap);


	javax.swing.GroupLayout jPanelGameStartLayout = new javax.swing.GroupLayout(this);
    this.setLayout(jPanelGameStartLayout);
    jPanelGameStartLayout.setHorizontalGroup(
        jPanelGameStartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanelGameStartLayout.createSequentialGroup()
            .addComponent(jTabbedPaneGame, javax.swing.GroupLayout.PREFERRED_SIZE, 562, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    jPanelGameStartLayout.setVerticalGroup(
        jPanelGameStartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jTabbedPaneGame)
    );
	
        jButtonSendCoor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSendCoorActionPerformed(evt);
            }
        });
	}


private void jButtonSendCoorActionPerformed(java.awt.event.ActionEvent evt) {
int x = Integer.parseInt(jTextFieldX.getText());
int y = Integer.parseInt(jTextFieldY.getText());
asm.sendMessage(new CoordsFromGUI(x,y),asm.getMyActorAddress());
	}

public void setClueText(String text){
	jLabelClueInput.setText(text);
	jLabelClueInput.setVisible(false);
	
	Painter<JXMapViewer> textOverlayClue = new Painter<JXMapViewer>() {
	    public void paint(Graphics2D g, JXMapViewer map, int w, int h) {
	        String inputString = getClueText();
	        g.setPaint(new Color(0,0,0,150));
	        g.fillRoundRect(20, 10, 462 , 30, 10, 10);
	        g.setPaint(Color.WHITE);
	        g.drawString(inputString, 20+10, 10+20);     
	    }
	    
	};
	jXMapKit1.getMainMap().setOverlayPainter(textOverlayClue);
}

public javax.swing.JTabbedPane getGameTabbePane(){
	return jTabbedPaneGame;
}

public String getThisGameName(){
	return gameName;
}

public String getClueText(){
	return jLabelClueInput.getText();
}

Painter<JXMapViewer> textOverlay = new Painter<JXMapViewer>() {
    public void paint(Graphics2D g, JXMapViewer map, int w, int h) {
        String inputString = getClueText();
        g.setPaint(new Color(0,0,0,150));
        g.fillRoundRect(20, 10, 462 , 30, 10, 10);
        g.setPaint(Color.WHITE);
        g.drawString(inputString, 20+10, 10+20);     
    }
    
};

Painter<JXMapViewer> textOverlayFoundTreasure = new Painter<JXMapViewer>() {
    public void paint(Graphics2D g, JXMapViewer map, int w, int h) {
        String inputString = "Congratulations, you located the treasure";
        g.setPaint(new Color(0,0,0,150));
        g.fillRoundRect(20, 10, 462 , 30, 10, 10);
        g.setPaint(Color.WHITE);
        g.drawString(inputString, 20+10, 10+20);
        
        
    }
    
};


Painter<JXMapViewer> textOverlayGameEnded = new Painter<JXMapViewer>() {
    public void paint(Graphics2D g, JXMapViewer map, int w, int h) {
        String inputString = "Congratulations, you located the treasure";
        g.setPaint(new Color(0,0,0,150));
        g.fillRoundRect(20, 10, 462 , 30, 10, 10);
        g.setPaint(Color.WHITE);
        g.drawString(inputString, 20+10, 10+20);
        
        
    }
    
};

private void jButtonViewClueActionPerformed(java.awt.event.ActionEvent evt) {
	// TODO add your handling code here:
    jXMapKit1.getMainMap().setOverlayPainter(textOverlay);
    jXMapKit1.setAddressLocation(new GeoPosition(63.43086,10.437012));
   // jXMapKit1.setZoom(14);
	
	
	
	}


	private void jButtonMyPositionActionPerformed(java.awt.event.ActionEvent evt) {
	// TODO add your handling code here:
		 jXMapKit1.setAddressLocation(new GeoPosition(63.43086,10.437012));
		 jXMapKit1.setMiniMapVisible(true);
		
		 System.out.println("inside my position event...");
		 
		Set<Waypoint> waypoints = new HashSet<Waypoint>();  
	    WaypointPainter painter = new WaypointPainter();
	   
        waypoints.add(new Waypoint(63.43086,10.437012));
        waypoints.add(new Waypoint(63.427021,10.37796));
	    painter.setWaypoints(waypoints);
	    
	    painter.setRenderer(new WaypointRenderer() {
	        public boolean paintWaypoint(Graphics2D g, JXMapViewer map, Waypoint wp) {
	          
	            String inputString = ("You are here");
	            g.setPaint(new Color(0,0,255,200));
	            Polygon triangle = new Polygon();
	            triangle.addPoint(0,0);
	            triangle.addPoint(11,11);
	            triangle.addPoint(-11,11);
	            g.fill(triangle);
	            int width = (int) g.getFontMetrics().getStringBounds(inputString, g).getWidth();
	            g.fillRoundRect(-width/2 -5, 10, width+10, 20, 10, 10);
	            
	            //draw text w/ shadow
	            g.setPaint(Color.BLACK);
	            g.drawString(inputString, -width/2-1, 26-1); //shadow
	            g.drawString(inputString, -width/2-1, 26-1); //shadow
	            g.setPaint(Color.WHITE);
	            g.drawString(inputString, -width/2, 26); //text
	            return false;
	            
	         
	        }
	    });
	       
	    jXMapKit1.getMainMap().setOverlayPainter(painter);
	    jXMapKit1.setZoom(5);
	    jXMapKit1.getMainMap().repaint();
	}

	public void foundTreasure(){
			jXMapKit1.getMainMap().setOverlayPainter(textOverlayFoundTreasure);
		    jXMapKit1.setAddressLocation(new GeoPosition(63.43086,10.437012));
		    jXMapKit1.setZoom(16);
		
	}
	
	public void gameEnded(final String score){
		jXMapKit1.getMainMap().setOverlayPainter(new Painter<JXMapViewer>() {
		    public void paint(Graphics2D g, JXMapViewer map, int w, int h) {
		        g.setPaint(new Color(0,0,0,150));
		        g.fillRoundRect(20, 10, 462 , 30, 10, 10);
		        g.setPaint(Color.WHITE);
		        g.drawString(score, 20+10, 10+20);
		        
		        
		    }
		    
		});
	    jXMapKit1.setAddressLocation(new GeoPosition(63.42, 10.40));
	    jXMapKit1.setZoom(16);
	}
	
	private void jButtonManUpdateActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
		asm.sendMessage(new ManuallyPosition(this), positionAgent);
		}

		private void jButtonAutoUpdateActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
		}
		
public void updateManCoord(double latitude, double longitude){
			
			
			System.out.println("Arrived latitude: "+latitude+" and longitude "+longitude);
			jXMapKit1.setAddressLocation(new GeoPosition(latitude, longitude));
			 jXMapKit1.setMiniMapVisible(false);
			
			Set<Waypoint> waypoints = new HashSet<Waypoint>();  
		    WaypointPainter painter = new WaypointPainter();
		   
		    playerPositions.put("me", new Waypoint(latitude, longitude));
		    
		    waypoints.add(new Waypoint(latitude, longitude));
		    painter.setWaypoints(waypoints);
		    painter.setRenderer(new WaypointRenderer() {
		        public boolean paintWaypoint(Graphics2D g, JXMapViewer map, Waypoint wp) {
		          
		            String inputString = ("You are here");
		            g.setPaint(new Color(0,0,255,200));
		            Polygon triangle = new Polygon();
		            triangle.addPoint(0,0);
		            triangle.addPoint(11,11);
		            triangle.addPoint(-11,11);
		            g.fill(triangle);
		            int width = (int) g.getFontMetrics().getStringBounds(inputString, g).getWidth();
		            g.fillRoundRect(-width/2 -5, 10, width+10, 20, 10, 10);
		            
		            //draw text w/ shadow
		            g.setPaint(Color.BLACK);
		            g.drawString(inputString, -width/2-1, 26-1); //shadow
		            g.drawString(inputString, -width/2-1, 26-1); //shadow
		            g.setPaint(Color.WHITE);
		            g.drawString(inputString, -width/2, 26); //text
		            return false;
		            
		         
		        }
		    });
		    jXMapKit1.getMainMap().setOverlayPainter(painter);
		    jXMapKit1.setZoom(5);
		    jXMapKit1.getMainMap().repaint();	
		}

public String getTeamLeader(){
	return groupLeader;
}

public void updateOtherCoord(double latitude, double longitude, String playerName){
	
	System.out.println("Arrived latitude: "+latitude+" and longitude "+longitude);
	jXMapKit1.setAddressLocation(new GeoPosition(latitude, longitude));
	jXMapKit1.setMiniMapVisible(false);
	
	playerPositions.put(playerName, new Waypoint(latitude, longitude));
	

	Set<Waypoint> waypoints = new HashSet<Waypoint>();  
    WaypointPainter painter = new WaypointPainter();
   
    Iterator<Map.Entry> iterator = playerPositions.entrySet().iterator();
	
	while(iterator.hasNext()){
		Map.Entry<String, Waypoint> me = (Map.Entry)iterator.next();
		waypoints.add(me.getValue());
		
	}
    
    
    painter.setWaypoints(waypoints);
    painter.setRenderer(new WaypointRenderer() {
        public boolean paintWaypoint(Graphics2D g, JXMapViewer map, Waypoint wp) {
          
            String inputString = "Player";
            g.setPaint(new Color(0,0,255,200));
            Polygon triangle = new Polygon();
            triangle.addPoint(0,0);
            triangle.addPoint(11,11);
            triangle.addPoint(-11,11);
            g.fill(triangle);
            int width = (int) g.getFontMetrics().getStringBounds(inputString, g).getWidth();
            g.fillRoundRect(-width/2 -5, 10, width+10, 20, 10, 10);
            
            //draw text w/ shadow
            g.setPaint(Color.BLACK);
            g.drawString(inputString, -width/2-1, 26-1); //shadow
            g.drawString(inputString, -width/2-1, 26-1); //shadow
            g.setPaint(Color.WHITE);
            g.drawString(inputString, -width/2, 26); //text
            return false;
            
         
        }
    });
    jXMapKit1.getMainMap().setOverlayPainter(painter);
    jXMapKit1.setZoom(5);
    jXMapKit1.getMainMap().repaint();
    
    
}


	

}

